package cn.tyoui.tool;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;

public class UPData {

    private Configuration conf;
    private FileSystem fs;
    private final URI HURI = URI.create("hdfs://" + IP.MASTER_IP + ":9000/");

    public UPData() {
        conf = new Configuration();
        conf.set("mapred.job.tracker", IP.MASTER_IP + ":9001");
        conf.set("fs.default.name", "hdfs://" + IP.MASTER_IP + ":9000");
        try {
            fs = FileSystem.get(HURI, conf);
        } catch (IOException e) {
        }
    }

    public List<String> getDateNodeHost() throws IOException {
        List<String> list = new ArrayList<>();
        DistributedFileSystem hdfs = (DistributedFileSystem) fs;
        DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats();
        for (int i = 0; i < dataNodeStats.length; i++) {
            list.add("Name:" + dataNodeStats[i].getHostName() + "-->");
        }
        return list;
    }

    public void upload(String s, String d) throws IOException {
        Path src = new Path(s);
        Path dst = new Path(d);
        fs.copyFromLocalFile(src, dst);
    }

    public void uploadDir(String localdir, String hdfspath) throws IOException {
        File file[] = new File(localdir).listFiles();
        for (File f : file) {
            if (f.isDirectory()) {
                hdfspath = hdfspath + File.separator + f.getName();
                mkdir(hdfspath);
                uploadDir(f.getAbsolutePath(), hdfspath);
            } else {
                Path src = new Path(f.getAbsolutePath());
                Path dst = new Path(hdfspath + File.separator + f.getName());
                fs.copyFromLocalFile(src, dst);
            }
        }
    }

    public boolean deleteHDFSFile(String dst) throws IOException {
        FileSystem hdfs = FileSystem.get(HURI, conf);
        boolean isDeleted = hdfs.delete(new Path(dst), true);
        hdfs.close();
        return isDeleted;
    }

    public boolean deleteDir(String dir) throws IOException {
        FileSystem fs = FileSystem.get(HURI, conf);
        boolean b = fs.delete(new Path(dir), true);
        fs.close();
        return b;
    }

    public boolean mkdir(String dir) throws IOException {
        FileSystem fs = FileSystem.get(HURI, conf);
        boolean b = fs.mkdirs(new Path(dir));
        fs.close();
        return b;
    }

}